package com.yl.framework.aspectj;

import cn.hutool.json.JSONUtil;
import com.yl.common.annotation.CacheResult;
import com.yl.common.core.redis.RedisCache;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * @author yuyu
 */
@Aspect
@Component
public class CacheAspect {
 
    @Autowired
    private RedisCache redisCache;
 
    @Around("@annotation(com.yl.common.annotation.CacheResult)")
    public Object cacheResult(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        CacheResult cacheResult = method.getAnnotation(CacheResult.class);


        // 尝试从缓存中获取数据
        Object cachedResult = redisCache.getCacheObject(cacheResult.key());
        if (cachedResult != null) {
            return cachedResult;
        }
//        JSONUtil.toBean(cachedResult.toString(),method.getReturnType());
        // 缓存未命中，执行方法并缓存结果
        Object result = joinPoint.proceed();
        if(result == null){
            return null;
        }
        
        redisCache.setCacheObject(cacheResult.key(), result,cacheResult.timeout(), cacheResult.timeunit());
        return result;
    }
}